package com.i2works.smartluolong.utils.common;

import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * 应用属性读取工具（读取application.properties）
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/1/27 0:07
 */
@Component
@PropertySource("classpath:apps.properties")
public class AppUtil {

    private static Map<String, Object> map = Maps.newHashMap();

    private static Environment env;

    private final Environment environment;

    @Autowired
    public AppUtil(Environment environment) {
        this.environment = environment;
    }

    @PostConstruct
    public void beforeInit() {
        env = environment;
    }


    /**
     * 返回object
     */
    public static String get(String key) {
        return execute(key, String.class);
    }

    /**
     * 返回指定类型
     */
    public static <T> T get(String key, Class<T> clazz) {
        return execute(key, clazz);
    }

    private static <T> T execute(String key, Class<T> clazz) {
        if (null == env || map.containsKey(key)) {
            return clazz.cast(map.get(key));
        }
        T property = env.getProperty(key, clazz);
        map.put(key, property);
        return property;
    }

}
